package io.netty.codec;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 *     writeAndFlush 两种使用区别:
 * <ul>
 * <li>ctx.channel().writeAndFlush 将从 Pipeline 的尾部 handler 开始往前找 OutboundHandler
 * <li>ctx.writeAndFlush 会从当前 handler 往前找 OutboundHandler
 * </ul>
 * </p>
 *
 * @author Verlet
 * @date 2023-02-06 21:42
 */
@Slf4j
public class ClientHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelActive(ChannelHandlerContext ctx) {
//        StudentPOJO.Student student = StudentPOJO.Student.newBuilder().setId(4).setName("张三").build();
//        ChannelFuture channelFuture = ctx.writeAndFlush(student);
        // 添加到TaskQueue中，任务是串行执行的和I/O同个线程
        ctx.channel().eventLoop().execute(() -> {
            MyDataInfo.MyMessage user = MyDataInfo.MyMessage.newBuilder().setDataType(MyDataInfo.MyMessage.DataType.UserType)
                    .setUser(MyDataInfo.User.newBuilder().setId(100).setName("王五").build()).build();
            ctx.channel().writeAndFlush(user);
            try {
                Thread.sleep(2 * 1000);
            } catch (InterruptedException e) {
                log.error(e.getMessage(), e);
            }
            MyDataInfo.MyMessage worker = MyDataInfo.MyMessage.newBuilder().setDataType(MyDataInfo.MyMessage.DataType.WorkerType)
                    .setWorker(MyDataInfo.Worker.newBuilder().setAge(20).setName("赵六").build()).build();
            ChannelFuture channelFuture = ctx.channel().writeAndFlush(worker);
            channelFuture.addListener(ChannelFutureListener.CLOSE);
        });

    }
}
